use std::fs::File;
use std::io::{BufRead, BufReader, Result};
use csv::ReaderBuilder;
use rand::Rng;
use std::thread;
use std::time::Duration;

#[derive(Debug, Clone)]
struct Word {
    word: String,
    meaning: String,
}

#[derive(Debug)]
struct DictationConfig {
    volume: f32,
    rate: f32,
    random_mode: bool,
    show_meaning: bool,
}

#[derive(Debug)]
struct DictationApp {
    words: Vec<Word>,
    current_index: usize,
    config: DictationConfig,
}

impl Default for DictationConfig {
    fn default() -> Self {
        Self {
            volume: 1.0,
            rate: 1.0,
            random_mode: false,
            show_meaning: true,
        }
    }
}

impl DictationApp {
    fn new() -> Self {
        Self {
            words: vec![],
            current_index: 0,
            config: DictationConfig::default(),
        }
    }

    fn load_sample_words(&mut self) -> Result<()> {
        let sample_content = "apple,苹果
book,书
computer,电脑
water,水
house,房子
car,汽车
school,学校
teacher,老师
student,学生
english,英语";

        let mut words = Vec::new();
        let mut reader = ReaderBuilder::new()
            .has_headers(false)
            .from_reader(sample_content.as_bytes());

        for result in reader.records() {
            let record = result?;
            if record.len() >= 2 {
                words.push(Word {
                    word: record[0].to_string(),
                    meaning: record[1].to_string(),
                });
            }
        }

        self.words = words;
        Ok(())
    }

    fn parse_csv(&mut self, file_path: &str) -> Result<()> {
        let file = File::open(file_path)?;
        let mut words = Vec::new();
        let mut reader = ReaderBuilder::new()
            .has_headers(false)
            .from_reader(file);

        for result in reader.records() {
            let record = result?;
            if record.len() >= 2 {
                words.push(Word {
                    word: record[0].to_string(),
                    meaning: record[1].to_string(),
                });
            }
        }

        self.words = words;
        Ok(())
    }

    fn parse_txt(&mut self, file_path: &str) -> Result<()> {
        let file = File::open(file_path)?;
        let reader = BufReader::new(file);
        let mut words = Vec::new();

        for line in reader.lines() {
            let line = line?;
            let line = line.trim();
            if line.is_empty() {
                continue;
            }

            // 匹配格式：word [meaning1;meaning2;meaning3]
            if let Some(start) = line.find('[') {
                if let Some(end) = line.find(']') {
                    let word = line[..start].trim().to_string();
                    let meanings: Vec<&str> = line[start + 1..end].split(';').collect();
                    let meaning = meanings.iter().map(|s| s.trim()).collect::<Vec<_>>().join("; ");

                    words.push(Word { word, meaning });
                }
            } else {
                // 如果不匹配特殊格式，则按空格分割处理
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 2 {
                    let word = parts[0].to_string();
                    let meaning = parts[1..].join(" ");

                    words.push(Word { word, meaning });
                }
            }
        }

        self.words = words;
        Ok(())
    }

    fn speak_word(&self, word: &str) {
        println!("播放单词: {}", word);
        // 在实际应用中，这里会调用系统的 TTS 引擎
        // 例如在 Linux 上使用 espeak，在 Windows 上使用 SAPI 等
        thread::sleep(Duration::from_millis((1000.0 / self.config.rate as f64) as u64));
    }

    fn next_word(&mut self) {
        if self.words.is_empty() {
            println!("词库为空");
            return;
        }

        if self.config.random_mode {
            let mut rng = rand::thread_rng();
            self.current_index = rng.gen_range(0..self.words.len());
        } else {
            self.current_index = (self.current_index + 1) % self.words.len();
        }

        let current_word = &self.words[self.current_index];
        self.speak_word(&current_word.word);
        println!("单词: {}", current_word.word);
        if self.config.show_meaning {
            println!("含义: {}", current_word.meaning);
        }
        println!("进度: {}/{}", self.current_index + 1, self.words.len());
    }

    fn prev_word(&mut self) {
        if self.words.is_empty() {
            println!("词库为空");
            return;
        }

        if self.current_index == 0 {
            self.current_index = self.words.len() - 1;
        } else {
            self.current_index -= 1;
        }

        let current_word = &self.words[self.current_index];
        self.speak_word(&current_word.word);
        println!("单词: {}", current_word.word);
        if self.config.show_meaning {
            println!("含义: {}", current_word.meaning);
        }
        println!("进度: {}/{}", self.current_index + 1, self.words.len());
    }

    fn show_current_word(&self) {
        if self.words.is_empty() {
            println!("词库为空");
            return;
        }

        let current_word = &self.words[self.current_index];
        println!("单词: {}", current_word.word);
        if self.config.show_meaning {
            println!("含义: {}", current_word.meaning);
        }
        println!("进度: {}/{}", self.current_index + 1, self.words.len());
    }

    fn toggle_random_mode(&mut self) {
        self.config.random_mode = !self.config.random_mode;
        println!(
            "随机模式已{}",
            if self.config.random_mode {
                "开启"
            } else {
                "关闭"
            }
        );
    }

    fn toggle_show_meaning(&mut self) {
        self.config.show_meaning = !self.config.show_meaning;
        println!(
            "显示含义已{}",
            if self.config.show_meaning {
                "开启"
            } else {
                "关闭"
            }
        );
    }

    fn set_rate(&mut self, rate: f32) {
        self.config.rate = rate.clamp(0.5, 2.0);
        println!("语速已设置为: {}x", self.config.rate);
    }

    fn run_interactive(&mut self) {
        println!("欢迎使用英语单词听写工具！");
        println!("输入命令:");
        println!("  n - 下一个单词");
        println!("  p - 上一个单词");
        println!("  c - 显示当前单词");
        println!("  r - 切换随机模式");
        println!("  m - 切换显示含义");
        println!("  s - 加载示例词库");
        println!("  1 - 设置语速为1x");
        println!("  2 - 设置语速为2x");
        println!("  q - 退出");

        loop {
            use std::io::{stdin, stdout, Write};
            print!("请输入命令: ");
            stdout().flush().unwrap();

            let mut input = String::new();
            stdin().read_line(&mut input).unwrap();
            let input = input.trim().to_lowercase();

            match input.as_str() {
                "n" => self.next_word(),
                "p" => self.prev_word(),
                "c" => self.show_current_word(),
                "r" => self.toggle_random_mode(),
                "m" => self.toggle_show_meaning(),
                "s" => {
                    if let Err(e) = self.load_sample_words() {
                        println!("加载示例词库失败: {}", e);
                    } else {
                        println!("示例词库已加载");
                        self.current_index = 0;
                    }
                }
                "1" => self.set_rate(1.0),
                "2" => self.set_rate(2.0),
                "q" => {
                    println!("再见！");
                    break;
                }
                _ => println!("无效命令，请重新输入"),
            }
        }
    }
}

fn main() -> Result<()> {
    let mut app = DictationApp::new();
    app.run_interactive();
    Ok(())
}